//
//  ReachabilityUtils.swift
//  AnJiBei
//
//  Created by 赵鑫 on 15/10/30.
//  Copyright © 2015年 赵鑫. All rights reserved.
//

import Foundation

import SystemConfiguration

enum connectedNetworkType {

    case GPRS,
    WIFI,
    NOCONNECT
}


class ReachabilityUtils {
    
    internal class func isConnectedToNetwork() -> Bool {
        
        var zeroAddress = sockaddr_in()
        zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
        
        zeroAddress.sin_family = sa_family_t(AF_INET)
        
        let defaultRouteReachability = withUnsafePointer(&zeroAddress){
        
            SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))

        }
        
        var flags = SCNetworkReachabilityFlags()
        
        if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
            return false
        }
        let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
        let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
        return (isReachable && !needsConnection)
    }
    
    internal class func isConnectedToNetworkOfType() ->connectedNetworkType {
    
        var zeroAddress = sockaddr_in()
        zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
        zeroAddress.sin_family = sa_family_t(AF_INET)
        
        let defaultRouteReachability = withUnsafePointer(&zeroAddress){
        
            SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
        }
        
        var flags = SCNetworkReachabilityFlags()
        
        if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
        
            return .NOCONNECT
        }
        
        debugPrint(flags.rawValue)
        
        debugPrint(kSCNetworkFlagsReachable)
        debugPrint(SCNetworkReachabilityFlags.IsWWAN.rawValue)
        //debugPrint(SCNetworkReachabilityFlags.IsDirect.rawValue)
        //debugPrint()

        

        
        let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
        let isWWAN = (flags.rawValue & UInt32(SCNetworkReachabilityFlags.IsWWAN.rawValue)) != 0
        
        if isReachable  {
        
            //流量
            if isWWAN {
            
                return .GPRS
            }
            
                //wift
            else {
            
                return .WIFI
            }
        }
        else {
        
            return .NOCONNECT
        }
        
        
       // return .NOCONNECT
        
    }
    
    internal class func  isConnectedToNetworkDebugPrint() {
        
        if isConnectedToNetwork() {
        
            PrintUntils.printLog("有网", message: "有网")
        }
        else {
        
            PrintUntils.printLog("没网", message: "没网")
        }
    
    }
}